﻿#include "mainwindow.h"
#include "./ui_mainwindow.h"
#include <QDebug>
#include <vector>
#include <QKeyEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect( ui->lineEdit_Search,SIGNAL(textChanged (const QString & )),this,SLOT(OnRadarChange(const QString & )));
    ui->lineEdit_Search->setPlaceholderText("plaese input search words.");
    vtCity.push_back("beijing1");
        vtCity.push_back("beijing2");
        vtCity.push_back("beijing3");
        vtCity.push_back("beijing4");
        vtCity.push_back("beijing5");
        vtCity.push_back("beijing6");
        vtCity.push_back("beijing7");
        vtCity.push_back("beijing8");
        vtCity.push_back("beijing9");
        vtCity.push_back("bengbu");
        vtCity.push_back("baise");

        ui->listWidget_Tips->addItem("123");
        ui->listWidget_Tips->addItem("123");
        ui->listWidget_Tips->addItem("123");
        ui->listWidget_Tips->setVisible(false);
}


MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::OnRadarChange(const QString &strText)
{

    QString searchQStr = ui->lineEdit_Search->text();
    qDebug()<<"searchKeyWord="<< searchQStr;
    std::string searchKeyWord =searchQStr.toStdString();
    //doSearchtipquery


    ui->listWidget_Tips->clear();
    for(int i = 0;i < vtCity.size();++i){

        if (vtCity[i].indexOf(strText) != -1)
        {

            ui->listWidget_Tips->addItem(vtCity[i]);
            qDebug()<<"vtCity["<<i<<"]="<<&vtCity[i];
        }
    }
    qDebug()<<"ui->listWidget_Tips->count()="<<ui->listWidget_Tips->count();
    if (ui->listWidget_Tips->count() > 0)
    {
        ui->listWidget_Tips->setVisible(true);
    }


}

void MainWindow::keyPressEvent(QKeyEvent *keyevent)
{
    qDebug()<<"focus:"<<(QApplication::focusWidget() !=ui->lineEdit_Search)<< "count:"<<ui->listWidget_Tips->count();
    if(QApplication::focusWidget() !=ui->lineEdit_Search ||  ui->listWidget_Tips->count() == 0){

        return;
    }
    int uKey = keyevent->key();
    qDebug()<<"uKey="<<uKey;
    Qt::Key key = static_cast<Qt::Key>(uKey);
    qDebug()<<"key="<<key;
    int iIndex =  ui->listWidget_Tips->currentRow ();
    qDebug()<<"index="<<iIndex;
    if(key == Qt::Key_Up)
    {
        iIndex--;
        if(iIndex < 0) iIndex = 0;
        QListWidgetItem *pItem =  ui->listWidget_Tips->item(iIndex);
        pItem->setForeground(Qt::red);
         ui->listWidget_Tips->setCurrentItem(pItem);

    }
    else if (key == Qt::Key_Down)
    {
        iIndex++;
        if(iIndex >=  ui->listWidget_Tips->count()) iIndex =  ui->listWidget_Tips->count() - 1;
        QListWidgetItem *pItem =  ui->listWidget_Tips->item(iIndex);
         ui->listWidget_Tips->setCurrentItem(pItem);
    }
    else if (key == Qt::Key_Enter || key == Qt::Key_Return)
    {
        ui->lineEdit_Search->setText( ui->listWidget_Tips->currentItem()->text());
        //dosearch
    }

}



